package com.hyf.rabbitmq.remoteRpc;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

public class RPCClient {

    private Connection connection;
    private Channel channel;
    private String requestQueueName="rpc_queue";
    private String replyQueueName;
    private QueueingConsumer consumer;
    public RPCClient() throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setUsername("admin");
        factory.setPassword("12345");
        factory.setVirtualHost("/");
        factory.setPort(5672);
        //第二种连接方式
        //factory.setUri("amqp://userName:password@hostName:portNumber/virtualHost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        replyQueueName = channel.queueDeclare().getQueue();
        consumer=new QueueingConsumer(channel);
        channel.basicConsume(replyQueueName,true,consumer);

    }

    public String call(String message) throws Exception {
        String response=null;
        String corrId=UUID.randomUUID().toString();
        AMQP.BasicProperties properties=new AMQP.BasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName).build();
        channel.basicPublish("",requestQueueName,properties,message.getBytes("utf-8"));
        while (true){
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            if(delivery.getProperties().getCorrelationId().equals(corrId)){
                response=new String(delivery.getBody(),"utf-8");
                break;
            }
        }
        return response;
    }

    public void close() throws IOException {
        connection.close();
    }

    public static void main(String[] args){

        RPCClient fibClientRpc=null;
        String response=null;

        try {
            fibClientRpc=new RPCClient();
            System.out.println("RPCClient [x] request fib(30)");
            response=fibClientRpc.call("30");
            System.out.println("RPCClient [.] got "+response+" ");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
